/**
 * Created by Administrator on 17-10-27.
 */
let P = require("bluebird");
let userDao = require('../dao/userDao');
let Token = require('../token');
let phttp = require('../util/phttp');
let iconst = require('../iconst');
let cnst = require('../const');
let fileUtil = require('../util/fileUtil');
let ipUtil = require('../util/ipUtil');
let io = require('socket.io-client');
let wxPayment = require('wx-payment');
let robotNames = require("../robotNames");
let newNames = require('../newnames');
let images = require('../images');
//let jiGuangSmsUtil = require('../util/JiGuangSmsUtil');
let redis = require('../dao/redis');

let clubMemberDao = require('../dao/ClubMemberDao');

const userService = require('../service/userService');
const gameService = require('../service/gameService');
let smsService = require('../service/SmsService');

//const { BusiError, SysError } = require('../exception/exception');

const { BusiError, SysError, ErrorResult } = require('../exception/exception');

let clubMemberService = require('../service/ClubMemberService');
let clubInfoDao = require('../dao/ClubInfoDao');

let roomCacheService = require('../service/RoomCacheService');

let clubCardsUpdateRecordDao = require('../dao/ClubCardsUpdateRecordDao');
let clubCoinsUpdateRecordDao = require('../dao/ClubCoinsUpdateRecordDao');

let agentService = require('../service/AgentService');

wxPayment.init({
    appid: cnst.wx_appid,
    mch_id: cnst.wx_mchid,
    apiKey: cnst.wx_appPaySecret, //微信商户平台API密钥
    //pfx: fs.readFileSync('./apiclient_cert.p12'), //微信商户平台证书 (optional，部分API需要使用)
});

let router = require('../router/Router');

router.getPhoneCode = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let uid = -1;
    let phone = req.query.phone;
    let code = req.query.code;
    try {
        uid = Token.aesDecodeDef(token);
    }
    catch (e) {
        uid = -1;
    }
    let url = cnst.url_getPhoneCode + '&mobile=' + phone + "&state=3";
    //{"errcode":0,"errmsg":"353253"}
    let tick = yield redis.getHashItem('phoneMap', phone);
    if (tick == null) tick = 0;
    let time = (new Date().getTime() - tick) / 1000;
    if (time < 60) {
        console.logw('getPhoneCode 60秒内不能重复获取验证码', uid);
        res.send({ code: 500, msg: '60秒内不能重复获取验证码 ' });
        return;
    }

    let userInfo = yield userDao.getInfoByPhone(phone);
    //没有用户的信息
    if (!userInfo && uid == -1) {
        console.logw('getPhoneCode 没有关联的用户信息', uid);
        res.send({ code: 500, msg: '请先绑定微信' });
        return;
    }
    console.log('userInfo', userInfo);
    if (userInfo)
        uid = userInfo.uid;

    if (userInfo && userInfo.phone === phone) {
        //console.logw('getPhoneCode 用户已绑定手机，请输入验证码',uid);
        //res.send({code:500,msg:'用户已绑定手机，请输入验证码'});
        //return;
    }
    let ret = yield phttp.httpGetAsync(url);
    console.log("get result", url, ret);
    let info = null;
    try {
        if (typeof ret === "string")
            info = JSON.parse(ret);
        else info = ret;
    }catch (e) {
        info = null;
        res.send({ code: 500, msg: '获取手机验证码失败' });
        return;
    }
    if (!info || info.errcode !== 0) {
        res.send({ code: 500, msg: '获取手机验证码失败' });
        return;
    }
    yield redis.setHashItem('phoneMap', phone, new Date().getTime());
    //let  code=fileUtil.randomCode(6);
    code = info.errmsg;
    if (uid !== -1 && uid != null) {
        let ret = yield userDao.setUserCheckCode(uid, phone, code);
        if (ret === -1) {
            res.send({ code: 500, msg: '用户已请求过手机关联验证码，不能绑定新的手机号' });
            return;
        }
        if (ret === -2) {
            console.logw('setUserCheckCode error', phone, code, uid);
            res.send({ code: 500, msg: '没有用户相关信息' });
            return;
        }
        console.logg('getphoneCode ', phone, code, uid);
        res.send({ code: 200, msg: '获取验证码成功' });
        return;
    }
    let ip = ipUtil.getIp(req);
    //let ret=yield app.userDao.updatePhoneCodeNoCheck(phone,code,ip);
    console.logg('phone ', phone, code, uid);
    res.send({ code: 200, msg: '请查看手机短信验证码' });
});

//http://weixin.g9527.com:3013/weixin/getPhoneCode?phone=13564547975&token=09439d9931f20f26199fa0b0d414e5df
router.get('/weixin/getPhoneCode', function (req, res) {
    router.getPhoneCode(req, res).catch(function (e) {
        console.logg('getPhoneCode 充值异常', e.message);
        if (!res.finished)
            res.send({ code: 500, msg: 'exception ' });
    });
});

router.getinviteInfo = P.coroutine(function* (req, res) {
    let inviteUid = req.query.inviteUid;
    let token = req.query.token;
    let uid = Token.aesDecodeDef(token);
    if (uid < 10) {
        res.send({ code: 500, msg: 'invalid uid' });
        return;
    }
    let suid = String(inviteUid);
    if (suid.length > 20) {
        res.send({ code: 500, msg: 'invalid param' });
        return;
    }
    let info = yield redis.getHashItem('weixinCache', inviteUid);
    if (!info) {
        info = yield userDao.getUserByIdAsync(inviteUid);
        if (!info) {
            res.send({ code: 500, msg: 'invalid invite uid' });
            return;
        }
    }else
        info = JSON.parse(info);
    res.send({ code: 200, uid: info.uid, name: info.name, wxNickName: info.wxNickName, headimgurl: info.headimgurl });
});

router.get('/weixin/getinviteInfo', function (req, res) {
    router.getinviteInfo(req, res).catch(function (e) {
        console.logg('agreeFriend 异常', e.message);
        res.send({ code: 500, msg: 'exception ' });
    });
});

router.bindPhone = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let phoneCode = req.query.code;
    let phone = req.query.phone;
    //let name = req.query.name;
    //let ID = req.query.ID;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
        if(typeof uid === "string"){
            let myuid = JSON.parse(uid);
            uid = myuid.uid;
        }
    } catch (e) { uid = -1; }
    if (uid === -1) {
        console.logw('bindPhone invalid uid');
        res.send({ code: 500, msg: '无效的token' });
        return;
    }

    let err = {};
    yield smsService.validPwdCode(phone, phoneCode);
    //console.logg("绑定手机不再赠送房卡,",phoneCode,phone,name,ID);
   // yield userDao.insertUserIDentity(ID, uid, phone, name);
    let ret = yield userDao.bindPhone(uid, phone, phoneCode, err);
    if (!ret) {
        console.logw('bindPhone failed');
        res.send({ code: 500, msg: err.msg });
        return;
    }
    res.send({ code: 200, msg: '绑定成功' });
});

router.get('/weixin/bindPhone', function (req, res) {
    router.bindPhone(req, res).catch(function (e) {
        console.logg('bindPhone 异常', e.message);
        let msg = "绑定失败";
        if(e instanceof BusiError){
            msg = e.message;
        }
        res.send({ code: 500, msg: msg });
    });
});

router.getGameRecord = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let page = req.query.page;
    let queryType = req.query.queryType;
    let uid = -1;
    try { uid = Token.aesDecodeDef(token); }catch (e) { uid = -1; }
    if (uid === -1) {
        console.logw('getGameRecord invalid uid');
        res.send({ code: 500, msg: 'invalid uid' });
        return;
    }
    let ret;
    if (queryType === 0)
        ret = yield router.getGameRecordFast(uid, page);
    //ret=yield app.userDao.getGameRecord(uid,page);

    //    if(queryType==1)
    //        ret=yield app.userDao.getMyGameRecord(uid,page);
    if (queryType === 1)
        ret = yield router.getMyGameRecordFast(uid, page);
    res.send({ code: 200, msg: "success", list: ret });
});

router.get('/weixin/getGameRecord', function (req, res) {
    router.getGameRecord(req, res).catch(function (e) {
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});

router.getGameInfo = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let roomTick = req.query.code;
    let uid = -1;
    try { 
        uid = Token.aesDecodeDef(token); 
    } catch (e) { uid = -1; }
    if (uid === -1) {
        console.logw('getGameInfo invalid uid');
        res.send({ code: 500, msg: 'invalid uid' });
        return;
    }
    if (!roomTick || roomTick.length > 50) {
        console.logw('getGameInfo invalid roomTick');
        res.send({ code: 500, msg: 'invalid roomTick' });
        return;
    }
    let ret = yield userDao.getGameRecordByRoomId(uid, roomTick);
    res.send({ code: 200, info: ret });

});

router.get('/weixin/getGameInfo', function (req, res) {
    router.getGameInfo(req, res).catch(function (e) {
        console.logw('getGameInfo exception ', e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});


router.random = function (min, max) {
    let n = max - min;
    if (n < 0) return 0;
    let ret = Math.floor(Math.random() * n) + min;
    return ret;
};

router.getRoomInfo = async function (uid) {
    let info = await redis.getHashItemHashItem(iconst.userRoomInfo, uid);
    return info;
};

router.get('/weixin/queryRoomInfo', function (req, resp) {
    let createData = decodeURIComponent(req.query.createData);
    let token = req.query.token;
    if (!createData) {
        resp.send({ code: 500, msg: '创建参数为空' });
        return;
    }
    if (createData.length > 512) {
        resp.send({ code: 500, msg: '创建参数长度太长' });
        return;
    }
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
    } catch (e) {
        uid = -1;
    }
    if (uid === -1 || uid == null) {
        console.logw('createRoomJinKu invalid uid');
        resp.send({ code: 500, msg: 'invalid uid' });
        return;
    }

    router.getRoomInfo(uid).then(res => {
        if (res) {
            resp.send({ code: 200, msg: 'success', data: res });
        } else {
            resp.send({ code: 500, msg: '查询失败' });
        }
    }).catch(e => {
        console.logw(e);
        resp.send({ code: 500, msg: '系统异常:' + e });
    });
});

// //金酷棋牌创建房间逻辑
// router.createRoomJinKu = P.coroutine(function* (req, res) {
//     let createData = decodeURIComponent(req.query.createData);
//     let token = req.query.token;
//     if (!createData) {
//         res.send({ code: 500, msg: '创建参数为空' });
//         return;
//     }
//     if (createData.length > 512) {
//         res.send({ code: 500, msg: '创建参数长度太长' });
//         return;
//     }
//     let uid = -1;
//     try {
//         uid = Token.aesDecodeDef(token);
//     } catch (e) { uid = -1; }
//     if (uid === -1 || uid == null) {
//         console.logw('createRoomJinKu invalid uid');
//         res.send({ code: 500, msg: 'invalid uid' });
//         return;
//     }
//     try {
//         createData = JSON.parse(createData);
//     }catch (e) {
//         createData = null;
//         res.send({ code: 500, msg: '无效的创建参数' });
//         return;
//     }

//     let gameType = createData.gameType;//niuniu,jinhua,
//     if (router.gameHostInfo == undefined) {
//         router.gameHostInfo = { tick: new Date().getTime(), hostMap: {}, listMap: {} }
//         let mapList = yield redis.scanMap(iconst.gameHost, 1, 200);
//         let list = mapList[1];
//         let len = list.length / 2;
//         for (let i = 0; i < len; i++) {
//             let ip = list[i * 2];
//             let info = list[i * 2 + 1];
//             info = JSON.parse(info);
//             if (!info) continue;
//             //{active:1,gameType:niuniu,onlineUser:0,userCapacity:100}
//             info.host = ip;
//             //{active:1,gameType:niuniu,onlineUser:0,userCapacity:100}
//             let l = router.gameHostInfo.listMap[info.gameType];
//             if (l === undefined) {
//                 router.gameHostInfo.listMap[info.gameType] = [];
//                 l = router.gameHostInfo.listMap[info.gameType];
//             }
//             if (info.active === 1) { l.push(info); }
//         }

//     } else {
//         let time = (new Date().getTime() - router.gameHostInfo.tick) / 1000;
//         if (time > 10) {
//             router.gameHostInfo = { tick: new Date().getTime(), hostMap: {}, listMap: {} };
//             let mapList = yield redis.scanMap(iconst.gameHost, 1, 200);
//             let list = mapList[1];
//             let len = list.length / 2;
//             for (let i = 0; i < len; i++) {
//                 let ip = list[i * 2];
//                 let info = list[i * 2 + 1];
//                 info = JSON.parse(info);
//                 if (!info) continue;
//                 //{active:1,gameType:niuniu,onlineUser:0,userCapacity:100}
//                 info.host = ip;
//                 let l = router.gameHostInfo.listMap[info.gameType];
//                 if (l === undefined) {
//                     router.gameHostInfo.listMap[info.gameType] = [];
//                     l = router.gameHostInfo.listMap[info.gameType];
//                 }
//                 if (info.active === 1) { l.push(info); }
//             }
//         }
//     }

//     let hostList = router.gameHostInfo.listMap[gameType];
//     if (hostList === undefined) {
//         res.send({ code: 500, msg: '没有找到' + gameType + "的主机" });
//         return;
//     }
//     let host = hostList[0].host;
//     if (host === undefined) {
//         res.send({ code: 500, msg: '没有找到' + gameType + "的主机" });
//         return;
//     }

//     if (uid) {
//         let uidObj = JSON.parse(uid);
//         if (uidObj.uid) {
//             uid = uidObj.uid;
//         }
//     }
//     let userinfo = yield userDao.getUserByIdAsync(uid);
//     if (!userinfo) userinfo = yield userDao.getGuestUserByUid(uid);
//     if (!userinfo) {
//         console.logg('无法获得用户信息');
//         res.send({ code: 500, msg: '无法获得用户信息' });
//         return;
//     }
//     if (userinfo.coinNum < 20 || userinfo.coinNum < createData.minEnterCoin) {
//         console.logg('玩家游戏币不足不能创建房间 name=' + userinfo.name + " coin=" + userinfo.coinNum);
//         res.send({ code: 500, msg: '玩家游戏币不足不能创建房间 name=' + userinfo.name + " coin=" + userinfo.coinNum });
//         return;
//     }

//     let userRoomInfo = yield redis.getHashItem(iconst.userRoomInfo, uid);
//     if (userRoomInfo) {
//         let roomInfo = yield redis.getHashItem(iconst.gameHistorySytx, 'room_' + userRoomInfo.roomId);
//         if (roomInfo) {
//             userRoomInfo = JSON.parse(userRoomInfo);
//             res.send({ code: 500, msg: "已经在别的房间:" + userRoomInfo.roomId });
//             return;
//         }

//         yield redis.delHashItem(iconst.userRoomInfo, uid);
//     }

//     let randomId, roomInfo;
//     for (let i = 0; i < 3; i++) {
//         randomId = this.random(100000, 999999);
//         roomInfo = yield redis.getHashItem(iconst.gameHistorySytx, 'room_' + randomId);
//         if (roomInfo == null) { break; }
//     }
//     if (roomInfo != null) {
//         res.send({ code: 500, msg: "创建房间失败,房间号冲突" });
//         return;
//     }
//     let n = new Date().getTime();
//     let data = {};
//     createData.tick = n;
//     roomInfo = {
//         owner: uid, roomId: randomId, roomPsw: randomId, tick: n, gameType: createData.gametype,
//         createData: createData, host: host
//     };
//     let uuid = 'room_' + randomId;
//     let s = JSON.stringify(roomInfo);
//     yield redis.setHashItem(iconst.gameHistorySytx, uuid, s);
//     yield redis.setHashItem(iconst.userRoomInfo, uid, s);

//     res.send({ code: 200, msg: "success", roomId: randomId, tick: n, host: host, roomInfo: s });
// });

// //金酷棋牌的创建房间接口
// router.get('/weixin/createRoomJinKu', function (req, resp) {
//     let createData = decodeURIComponent(req.query.createData);
//     let token = req.query.token;
//     if (!createData) {
//         resp.send({ code: 500, msg: '创建参数为空' });
//         return;
//     }

//     if (createData.length > 512) {
//         resp.send({ code: 500, msg: '创建参数长度太长' });
//         return;
//     }

//     let uid = -1;
//     try {
//         uid = Token.aesDecodeDef(token);
//     } catch (e) {
//         uid = -1;
//     }

//     if (uid === -1 || uid == null) {
//         console.logw('createRoomJinKu invalid uid');
//         resp.send({ code: 500, msg: 'invalid uid' });
//         return;
//     }
//     try {
//         createData = JSON.parse(createData);
//     } catch (e) {
//         createData = null;
//         resp.send({ code: 500, msg: '无效的创建参数' });
//         return;
//     }

//     gameService.createGameRoom(uid, createData).then(res => {
//         res.code = 200;
//         res.msg = "success";
//         resp.send(res);
//     }).catch(err => {
//         let msg = "系统异常, 请稍后再试";
//         if (err instanceof BusiError){
//             msg = err.message;
//         }

//         resp.send({code: 500, msg: msg});
//     });
// });

router.releaseRoom = P.coroutine(function* (req, res) {
    let uid = req.query.uid;
    let roomId = req.query.roomId;
    let tick = req.query.tick;
    let uuid = 'room_' + roomId;
    let roomInfo = yield redis.getHashItem(iconst.gameHistorySytx, uuid);
    console.logw('roomInfo ', roomInfo);
    try {
        let roomInfo = JSON.parse(roomInfo);
        let createData = roomInfo.createData;
        if (typeof createData === 'string') {
            createData = JSON.parse(createData);
        }
        if (createData.clubId) {
            let data = { event: iconst.netEvent.destroyRoom, clubId: createData.clubId, roomId: roomId };
            console.logw("发送解散房间时时通知 ", data);
            router.rpcIo.sendMsg("niuniuClub", data);
        }
    }
    catch (e) {
        console.logw('解析 roomInfo 失败 ', e.message);
    }
    yield redis.delHashItem(iconst.gameHistorySytx, uuid);
    res.send({ code: 200, msg: "success", roomId: roomId, tick: tick });
});

//http://weixin.g9527.com:3013/weixin/releaeRoom?roomId=866986
router.get('/weixin/releaeRoom', function (req, res) {
    router.releaseRoom(req, res).catch(function (e) {
        console.logw('releaeRoom exception ', e.message)
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});

router.userLeaveRoom = P.coroutine(function* (req, res) {
    let uid = req.query.uid;
    let uuid = 'user_' + uid;
    let roomId = req.query.roomId;
    let tick = req.query.tick;
    yield redis.delHashItem(iconst.gameHistorySytx, uuid);
    res.send({ code: 200, msg: "success" });
});

//http://weixin.g9527.com:3013/weixin/userLeaveRoom?roomId=488637&uid=100117&tick=123456
//http://game.0859qp.com/weixin/userLeaveRoom?uid=1000
router.get('/weixin/userLeaveRoom', function (req, res) {
    router.userLeaveRoom(req, res).catch(function (e) {
        console.logw('userLeaveRoom exception ', e.message)
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});

router.userEnterRoom = P.coroutine(function* (req, res) {
    let uid = req.query.uid;
    let roomId = req.query.roomId;
    let tick = req.query.tick;
    let key = 'user_' + uid;
    let uuid = 'room_' + roomId;
    yield redis.setHashItem(iconst.gameHistorySytx, key, uuid);
    res.send({ code: 200, msg: "success", roomId: roomId, tick: tick });
});

//http://weixin.g9527.com:3013/weixin/userEnterRoom?roomId=488637&uid=100117&tick=123456
router.get('/weixin/userEnterRoom', function (req, res) {
    router.userEnterRoom(req, res).catch(function (e) {
        console.logw('userEnterRoom exception ', e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});


router.queryUserRoom = P.coroutine(function* (req, res) {
    let uid = req.query.uid;
    let key = 'user_' + uid;
    let roomId = yield redis.getHashItem(iconst.gameHistorySytx, key);
    if (!roomId) {
        res.send({ code: 200, msg: "用户不在房间内" });
        return;
    }
    let roomInfo = yield redis.getHashItem(iconst.gameHistorySytx, roomId);
    res.send({ code: 200, msg: "success", roomId: roomId, roomInfo: roomInfo });
});


//http://weixin.g9527.com:3013/weixin/queryUserRoom?roomId=488637&uid=100117&tick=123456
router.get('/weixin/queryUserRoom', function (req, res) {
    router.queryUserRoom(req, res).catch(function (e) {
        console.logw('queryUserRoom exception ', e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});

router.queryRoom = P.coroutine(function* (req, res) {
    let roomId = req.query.roomId;
    let key = 'room_' + roomId;
    let roomInfo = yield redis.getHashItem(iconst.gameHistorySytx, key);
    if (!roomInfo) {
        res.send({ code: 200, msg: "user not in room" });
        return;
    }
    console.logg("queryRoom  ", key);
    setTimeout(function () {
        let key = this.toString();
        console.logg("delete room ", key);
        redis.delHashItem(iconst.gameHistorySytx, key);
    }.bind(key), 5 * 60 * 1000);
    res.send({ code: 200, msg: "success", roomId: roomId, roomInfo: roomInfo });
});


//http://weixin.g9527.com:3013/weixin/queryRoom?roomId=189945&uid=100117&tick=123456
//http://47.96.73.236:3015/weixin/queryRoom?roomId=160861
router.get('/weixin/queryRoom', function (req, res) {
    router.queryRoom(req, res).catch(function (e) {
        console.logw('queryRoom exception ', e.message)
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});

router.gameLogin = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let gameTick = req.query.tick;
    let gameRoomId = req.query.roomId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
    }catch (e) {
        console.logg('解析token信息失败');
        let msg = { code: 500, msg: '解析token信息失败' };
        res.send(msg);
        return;
    }
    let userInfo = yield router.getWechatCacheData(uid);
    if (!userInfo) {
        userInfo = yield userDao.getUserByIdAsync(uid);
        if (userInfo)
            yield router.cacheLoginInfo(uid, userInfo);
    }
    if (!userInfo) {
        res.send({ code: 500, msg: '无法获得用户信息' });
        return;
    }
    let time = (new Date().getTime() - userInfo.tick) / 1000;
    let day3 = 24 * 60 * 60 * 3;
    if (userInfo.ban !== undefined && userInfo.ban > 0) {
        console.logw('玩家', userInfo.name, '已被封号不能登陆');
        res.send({ code: 500, errmsg: '此号已封' });
        return;
    }

    let offlineData = ""; // yield router.getUserOfflineData(uid);
    let version = yield redis.getString("version");
    let cacheInfo = {};
    cacheInfo.token = token;
    cacheInfo.uid = uid;
    cacheInfo.offlineData = offlineData;
    cacheInfo.code = 200;
    cacheInfo.name = userInfo.name;
    cacheInfo.wxNickName = userInfo.wxNickName;
    cacheInfo.headimgurl = userInfo.headimgurl;
    cacheInfo.cardNum = userInfo.cardNum;
    cacheInfo.phone = userInfo.phone; cacheInfo.phoneCode = userInfo.phoneCode; cacheInfo.codeNocheck = userInfo.codeNocheck;
    let roomId = yield redis.getHashItem(iconst.gameHistoryName, 'user_' + uid);
    cacheInfo.roomId = roomId;
    cacheInfo.version = version;
    if (gameTick && gameRoomId) {
        // if (gameType == "xymj") {
        //     let gameHistoryInfo = yield router.getGameZhanji(gameTick, gameRoomId);
        // } else {
        //     let gameHistoryInfo = yield router.getGameInfoByDate(gameTick, gameRoomId);
        // }
        // cacheInfo.gameHistoryInfo = gameHistoryInfo;
        let enterRoomInfo = yield redis.getHashItem(iconst.gameHistoryName, "room_" + gameRoomId);
        cacheInfo.enterRoomInfo = enterRoomInfo;
    }
    cacheInfo.phoneNoCheck = 1;
    cacheInfo.sex = userInfo.sex;
    cacheInfo.debugFlag = userInfo.debugFlag;
    if (cacheInfo.phoneCode == cacheInfo.codeNocheck && cacheInfo.phoneCode) cacheInfo.phoneNoCheck = 0;
    console.logw('cachInfo 539', JSON.stringify(cacheInfo));
    res.send(cacheInfo);

});
router.get('/weixin/gameLogin', function (req, res) {
    router.gameLogin(req, res).catch(function (e) {
        console.logw('gameLogin exception ', e.message);
        if (!res.finished) { res.send({ code: 500, msg: "exception" }); }
    });
});


router.guestReigister = P.coroutine(function* (req, res) {
    let ip = ipUtil.getIp(req, res);
    let imgurl = Math.floor(Math.random() * 83);
    let info = null;
    for (let i = 0; i < 3; i++) {
        info = yield userDao.createGuestUserAsync(imgurl, ip);
        if (info != null) {
            break;
        }
    }

    if (info == null) {
        res.send({ code: 500, msg: "create guest accout failed" });
        return;
    }
    let token = Token.aesEncodeDef(info.uid);
    let ret = { code: 200, uid: info.uid, token: token, headimgurl: imgurl, name: info.uid };
    res.send(ret);
});


router.get('/weixin/guestReigister', function (req, res) {
    router.guestReigister(req, res).catch(function (e) {
        if (!res.finished) {
            console.logw("guestReigister 发生异常 " + e.message);
            res.send({ code: 500, msg: "exception " });
        }
    });

});


router.RandomUid = function (len) {
    let $chars = '0123456789';
    let maxPos = $chars.length;
    let pwd = ''; for (let i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); }
    return pwd;
};

router.getRobot1 =function (req, res) {
    let tp = req.query.tp;
    if (tp !== "test_channel") {
        res.send({ code: 500, msg: "invalid tp" });
        return;
    }

    let uid = router.RandomUid(8);
    let list = ["http://wx.qlogo.cn/mmopen/Q3auHgzwzM76vZvtRiaAqJmWzJImIuqIx1HfZCbxICNicSiaicfBdSeKQ4evYXcOfoDhHibLrmOsmia5YpauFw7c9ybRZsqjbfJ5gv6h38ibQm11gw/0",
        "http://imgcache.g9527.com/006agRusjw8f7q0bgbyuqj30ro0rpwg5.jpg",
        "http://imgcache.g9527.com/006kSXONjw8fbq08uqailj30ig0ig415.jpg",
        "http://imgcache.g9527.com/006zfdGjjw8fbhfdiu28zj30hs0h4gmb.jpg",
        "http://imgcache.g9527.com/006BFxhFjw8fbtougnc1qj30ig0igjs1.jpg",
        "http://wx.qlogo.cn/mmopen/k0Ue4mIpaVicAXoZ3uiadCxaeJia2P1n1Puqz8cSmrYRjGzYplFpWyBaph981jQWUu2tD7hZwH29jDclN7sjAC3GQ/0",
        "http://thirdwx.qlogo.cn/mmopen/vi_32/mLeVgu0UljHiaCHumkXEibUuicEe1U3xjkDpMWUaiaGVGZXMQ3t0icvibjicCw0kSwBYwOxceEXCDZa0IaCfCquYHR5jg/132"];
    //1-83.png
    let n = Math.floor(Math.random() * (list.length - 1));
    let url = list[n];
    url = Math.floor(Math.random() * 82) + 1

    let coinNum = Math.floor(Math.random() * 100) + 50;
    let ret = { code: 200, uid: uid, name: uid, headimgurl: url, coinNum: coinNum }
    res.send(ret);
};

let robotMap = { time: new Date().getTime() };
router.getRobot =function(req, res) {
    let tp = req.query.tp;
    if (tp !== "test_channel") {
        res.send({ code: 500, msg: "invalid tp" });
        return;
    }

    if (((new Date().getTime() - robotMap.time) / 1000 / 60 > 60) ||
        robotMap.length >= robotNames.length) {
        robotMap = { time: new Date().getTime() };
    }

    let uid = router.RandomUid(8);
    let len = newNames.length;
    let n = Math.floor(Math.random() * (len - 1));
    if (robotMap[n]) {
        let robot = robotMap[n];
        let t = (new Date().getTime() - robot.time) / 1000 / 60;
        if (t < 5) {
            console.logw("robot id repeat");
            res.send({ code: 500, msg: "get robot err" });
            return;
        }
    }

    let item = newNames[n];
    item.time = new Date().getTime();
    robotMap[n] = item;

    let imgLen = images.length;
    let rImg = Math.floor(Math.random() * (len - 1));

    let url = Math.floor(Math.random() * 82) + 1;
    let coinNum = Math.floor(Math.random() * 100) + 50;

    let r = Math.floor(Math.random() * (4));
    let sex = 1;
    if (r === 1) {
        sex = 0;
    }

    let ret = { code: 200, uid: uid, name: item, headimgurl: images[rImg], coinNum: coinNum, sex: sex };
    res.send(ret);

};

router.get('/weixin/getRobot', function (req, res) {
    router.getRobot(req, res);
});

router.gameGuestLogin = P.coroutine(function* (req, res) {
    let uid = req.query.uid;
    let token = req.query.guesttoken;
    let ip = ipUtil.getIp(req, res);
    let gameType = req.query.gameType;
    let stoken = Token.aesEncodeDef(ip);
    let token0 = req.query.token;
    if (token0 && !token) {
        token = token0;
    }
    let os = '';
    let userDao = userDao;
    let debugMode = 0;
    if (uid && uid !== 'undefined') {
        console.log('调试模式', uid);
        debugMode = 1;
    }
    if (uid === 'undefined') uid = null;
    try {
        if (token && !uid)
            uid = Token.aesDecodeDef(token);
    }catch (e) { }
    if (uid === undefined || uid == null) {
        console.logw("invalid token ");
        res.send({ code: 500, msg: 'invlid token' });
        return;
    }
    let version = yield redis.getString("version");
    let resData = yield userDao.getGuestUserByUid(uid);
    if (!resData) {   //
        let resData = yield userDao.getUserByIdAsync(uid);
        if (!resData) {
            console.logw("get user info failed uid=" + uid);
            res.send({ code: 500, msg: 'guest login faield' });
            return;
        }

    }
    let url = yield router.getCoinGameUrl(uid, gameType)
    token = Token.aesEncodeDef(uid);
    let sex = resData.sex;
    if (sex !== 0 && sex !== 1) {
        sex = 1;
    }

    let ret = {
        code: 200,
        uid: uid,
        headimgurl: resData.headimgurl,
        coinNum: resData.coinNum,
        name: resData.name,
        ip: ip,
        token: token,
        stoken: stoken,
        version: version,
        gameUrl: url,
        bankCoin: resData.bankCoin,
        sex: sex
    };

    res.send(ret);
});

router.get('/weixin/gameGuestLogin', function (req, resp) {
    let uid = req.query.uid;
    let token = req.query.guesttoken;
    let ip = ipUtil.getIp(req, resp);
    let gameType = req.query.gameType;
    userService.loginByTokenOrUUID(token, uid, req.ip, req.ua, "").then(res => {
        res.code = 200;
        res.msg = "success";
        resp.send(res);
    }).catch(e => {
        let msg = "系统异常, 请稍后再试";
        console.logw("err:", e);
        if (e instanceof BusiError) {
            msg = e.message;
        }
        resp.send({ code: 500, msg: msg });
    });
});

//
router.get('/weixin/coingameLogin', function (req, resp) {
    let uid = req.query.uid;
    let token = req.query.token;
    let ip = ipUtil.getIp(req, resp);
    let gameType = req.query.gameType;
    userService.loginByTokenOrUUID(token, uid,  req.ip, req.ua, "").then(res => {
        res.code = 200;
        res.msg = "success";
        resp.send(res);
    }).catch(e => {
        let msg = "系统异常, 请稍后再试";
        console.logw("err:", e);
        if (e instanceof BusiError) {
            msg = e.message;
        }

        resp.send({ code: 500, msg: msg });
    });
});

router.setUserRoom = P.coroutine(function* (req, res) {
    let clubId = req.query.clubId;
    let roomId = req.query.roomId;
    let check = req.query.check;
    let uid = req.query.uid;
    let gameType = req.query.gameType;
    if (check != iconst.sysCheck) {
        res.send({ code: 500, msg: "invalid request" });
        return;
    }
    let key = gameType + '_' + uid;
    let obj = { clubId: clubId, gameType: gameType, roomId: roomId };
    let str = JSON.stringify(obj);
    yield redis.setString(key, str);
    yield redis.setExpire(key, 60 * 60); //一小时后自动删除
    res.send({ code: 200, msg: "finished" });
});

router.get('/weixin/setUserRoom', function (req, res) {
    router.setUserRoom(req, res).catch(function (e) {
        if (!res.finished) {
            console.logw("setUserRoom 发生异常 " + e.message);
            res.send({ code: 500, msg: "exception " });
        }
    });
});

router.getUserRoom = P.coroutine(function* (req, res) {
    let token = req.query.token;
    let gameType = req.query.gameType;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let key = gameType + '_' + uid;
    let str = yield redis.getString(key);
    res.send({ code: 200, info: str });
});

router.get('/weixin/getUserRoom', function (req, res) {
    router.getUserRoom(req, res).catch(function (e) {
        if (!res.finished) {
            console.logw("getUserRoom 发生异常 " + e.message);
            res.send({ code: 500, msg: "exception " });
        }
    });
});


//添加大联盟
router.judgeIsUnionOwner = P.coroutine(function*(unionId, uid, res){
    let union = yield  userDao.getUnionById(unionId);
    if(union == null || union.ownerUid != uid){
        //console.logw('updateUnion user no right');
        res.send({code: 500, msg: '用户无权限'});
        return false;
    }
    return true;
})

router.judgeIsUnionAdministrator = P.coroutine(function*(unionId, uid, res){
    let flag = yield userDao.judgeIsUnionAdministrator(unionId, uid);
    if(!flag){

        res.send({code: 500, msg: '用户无权限'});
        return false;
    }
    return true;
})

router.judgeIsUnionOwner2 = P.coroutine(function*(unionId, uid, res){
    let union = yield  userDao.getUnionById(unionId);
    if(union == null || union.ownerUid != uid){
        return false;
    }
    return true;
})

router.judgeIsUnionAdministrator2 = P.coroutine(function*(unionId, uid, res){
    let flag = yield userDao.judgeIsUnionAdministrator(unionId, uid);
    if(!flag){
        return false;
    }
    return true;
})

/**
 * 创建大联盟
 */
router.createUnion= P.coroutine(function*(req,res){
    let  token=req.query.token;
    let  unionName = req.query.unionName;

    if(unionName == null || unionName == '') {
        res.send({code:500,msg:"联盟名字不能为空"});
        return;
    }

    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }
    let myuid = JSON.parse(uid);

    // let myres = yield userDao.getUserByUid(myuid.uid);
    // if(myres) {
    //     let unionInfo = yield userDao.createUnion(myuid.uid, unionName, myres.name, myres.headimgurl);
    //     res.send({code: 200, msg:"success", unionInfo: unionInfo});
    //     return;
    // }

    //查找有没有同名
    let res1 = yield userDao.findUnionName(unionName);
    if(res1){
        res.send({ code: 500, msg: "大联盟名字已经存在，请重新换个名字" });
        return;
    }

    //查找是否有空的俱乐部
    let myres = yield userDao.getEmptyByID(myuid.uid);
    if(!myres || myres.length == 0){
        res.send({code: 500, msg:"请先创建一个新的俱乐部用于创建的大联盟"});
        return;
    }
    let unionInfo = yield userDao.createUnion(myuid.uid, unionName);
    //俱乐部加入大联盟
    yield userDao.updateClub4JoinUnion(unionInfo.unionId,myres.clubId);
    res.send({code: 200, msg:"success", unionInfo: unionInfo});
})

router.get('/weixin/union/create',function(req,res){
    router.createUnion(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("createUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 获取联盟列表
 */
router.listUnion = P.coroutine(function*(req,res){
    let token = req.query.token;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    let myuid = JSON.parse(uid);
    /*let clubList = yield userDao.listUnion2(myuid.uid);
    let clubList2 = yield userDao.listUnionJoin(myuid.uid);*/

    let unionList = yield userDao.listUsertUnion(myuid.uid);
 //   let unionList = yield userDao.listUnionJoin(myuid.uid);
    let systemUnionList = yield userDao.listSystemUnion(myuid.uid);

//    let clubList = yield userDao.listUnion("100118");

    res.send({code:200, msg:"success", unionList:unionList, systemUnionList: systemUnionList});
})

router.get('/weixin/union/list',function(req,res){
    router.listUnion(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("listUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 修改大联盟信息
 */
router.updateUnion= P.coroutine(function*(req,res){
    let  token=req.query.token;
    let  unionName = req.query.unionName;
    let unionId = req.query.unionId;
    let roomType = req.query.roomType;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    let myuid = JSON.parse(uid);
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner(unionId, myuid.uid, res);
    if(!flag){
        return;
    }
    let myres;
    if(unionName !== undefined){
        myres = yield userDao.updateUnionInfo(unionId, unionName);
    }
    if(!roomType !== undefined){
        myres = yield userDao.updateUnionRoomType(unionId, roomType);
    }
    if(myres){
        res.send({code:200,msg:"success ",unionInfo:unionName});
    }
    res.send({code:500,msg:"修改信息出现错误"});
})

router.get('/weixin/union/update',function(req,res){
    router.updateUnion(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("updateUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 修改大联盟的开房模式
 */
router.get('/weixin/union/updateRoomType',function(req,res){
    router.updateUnion(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("dissolveUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

/**
 * 获取大联盟详细信息
 * @type {Function}
 */
router.getUnionInfo = P.coroutine(function*(req,res){
    let  token=req.query.token;
    let unionId = req.query.unionId;
    let unioninfo = yield userDao.getUnionInfo(unionId);
    res.send({code:200,msg:"success ", unioninfo: unioninfo});
})

router.get('/weixin/union/detail',function(req,res){
    router.getUnionInfo(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("updateUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 获取大联盟管理员列表
 * @type {(function(): *)|Function}
 */
router.getUnionAdministratorList= P.coroutine(function*(req,res){
    let  token=req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner(unionId, myuid.uid, res);
    if(!flag){
        return;
    }

    let adminList = yield userDao.getUnionAdministratorList(unionId);
    res.send({code: 200, msg:"success", adminList: adminList});
})

router.get('/weixin/union/administrator/list', function(req,res){
    router.getUnionAdministratorList(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("getUnionAdministratorList 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 任命管理员
 * @type {(function(): *)|Function}
 */
router.addUnionAdministrator = P.coroutine(function*(req,res){
    let  token=req.query.token;
    let unionId = req.query.unionId;
    let adminUid = req.query.adminUid;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    let myuid = JSON.parse(uid);
    let adminUser = yield userDao.getUserByUid(adminUid);
    if(adminUser == null){
        res.send({code:500,msg:"用户不存在"});
        return;
    }
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner(unionId, myuid.uid, res);
    if(!flag){
        return;
    }
    yield userDao.addUnionAdministrator(unionId, adminUid, 2);

    let member = { msgType:52, admin:adminUid, unionId:unionId };
    let s=JSON.stringify(member);
    yield redis.publishUnion(s);

    res.send({code: 200, msg:"success"});
})

router.get('/weixin/union/administrator/add', function(req, res){
    router.addUnionAdministrator(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("addUnionAdministrator 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 删除联盟管理员
 * @type {(function(): *)|Function}
 */
router.deleteUnionAdministrator = P.coroutine(function*(req, res){
    let  token=req.query.token;
    let unionId = req.query.unionId;
    let adminUid = req.query.adminUid;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner(unionId, myuid.uid, res);
    if(!flag){
        return;
    }
    yield userDao.deleteUnionAdministrator(unionId, adminUid, myuid.uid);
    res.send({code: 200, msg:"success"});
})

router.get('/weixin/union/administrator/delete', function(req, res){
    router.deleteUnionAdministrator(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("deleteUnionAdministrator 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

router.getUnionRecord = P.coroutine(function*(req, res){

})

router.get('/weixin/union/record', function(req, res){
    router.getUnionRecord(req, res).catch(function(e){
        if(!res.finished) {
            console.logw("getUnionRecord 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 盟主获取联盟的俱乐部列表
 */
router.listUnionClub = P.coroutine(function*(req,res){
    let token = req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);

    let clubList = yield userDao.listUnionClub(unionId);
    res.send({code:200, msg:"success", aclubList:clubList});
})

router.get('/weixin/union/club/list',function(req,res){
    router.listUnionClub(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("qclubList 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 玩家获取联盟的俱乐部列表
 */
router.listUnionClubPlayer = P.coroutine(function*(req,res){
    let token = req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);
    let clubList = yield userDao.listUnionClubPlayer(myuid.uid, unionId);
    res.send({code:200, msg:"success", aclubList:clubList});
})

router.get('/weixin/union/club/list/player',function(req,res){
    router.listUnionClubPlayer(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("qclubList 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 俱乐部群主获取联盟里属于自己的俱乐部列表
 */
// router.listUnionClubOwner = P.coroutine(function*(req,res){
//     let token = req.query.token;
//     let unionId = req.query.unionId;
//     let uid = -1;
//     try {
//         uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
//     } catch (e) {
//         console.logw('decode token failed ', token, 'uid', uid);
//         uid = -1;
//     }
//     if (uid === -1) {
//         res.send({ code: 500, err: "invalid uid" });
//         return;
//     }
//
//     let myuid = JSON.parse(uid);
//     let clubList = yield userDao.listUnionClubPlayer(myuid.uid, unionId);
//     res.send({code:200, msg:"success", aclubList:clubList});
// })
//
// router.get('/weixin/union/club/list/owner',function(req,res){
//     router.listUnionClubOwner(req,res).catch(function(e) {
//         if(!res.finished) {
//             console.logw("qclubList 发生异常 "+ e.message);
//             res.send({code:500,msg:"exception "});
//         }
//     });
// })

/**
 * 大联盟发放或减少俱乐部的疲劳币
 * @type {(function(): *)|Function}
 */
router.unionIssueCoin2Club = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let unionId = req.query.unionId;
    let clubId = req.query.clubId;
    let coinAmount = req.query.coinAmount;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let isOwner = true;
    let myuid = JSON.parse(uid);
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner2(unionId, myuid.uid, res);
    if(!flag){
     //   return;
        isOwner = false;
        //判断是不是管理员
        let flag2 = yield router.judgeIsUnionAdministrator2(unionId, myuid.uid, res);
        if(!flag2){
            res.send({code: 500, msg: '用户无权限'});
            return;
        }
    }
    //判断该俱乐部属不属于联盟
    let club = yield userDao.getClubInfoById(clubId);
    if(!club || club.unionId !== unionId){
        console.logw('updateUnion union no right');
        res.send({code: 500, msg: '该俱乐部不属于联盟成员'});
        return;
    }
    if(!isOwner){
        //管理员操作
        let resAdmin = yield userDao.selectUnionAdministrator(unionId, myuid.uid);
        if(resAdmin){
            if(parseInt(resAdmin.coins) < parseInt(coinAmount)){
                //管理员联盟币不足以操作联盟币
                res.send({code: 501, msg: '您管理员联盟币不够，不能进行此操作'});
                return;
            }else{
                //修改管理员联盟币
                yield userDao.qudateUnionAdminCoins(unionId, myuid.uid,coinAmount,'');
            }
        }else{
            res.send({code: 500, msg: '您不是管理员或被冻结，不能进行此操作'});
            return;
        }
    }

    //组织一个字符串
    let fName = '盟主 ';
    if(!isOwner){
        fName = '管理员 ';
    }
    fName = fName +'(' + myuid.uid + ') 给合伙人 ' + club.clubName +'(' + club.clubId + ') ' + '加'+ coinAmount +'分数';

    //群主操作
    let bool = yield userDao.unionIssueCoin2Club(unionId, clubId, coinAmount, fName);
    if(bool){
        //广播
        let club =yield userDao.getClubInfoById(clubId);
        if(club != null){
            let unionCoin = club.unionCoin;
            if(unionCoin== null){
                unionCoin = 0;
            }
            let member = { msgType:55, unionId:unionId, clubId:clubId, coin:unionCoin };
            let s=JSON.stringify(member);
            yield redis.publishUnion(s);
        }

        res.send({code:200,msg:"success "});
    }else{
        res.send({code:500,msg:"exception "});
    }

})



router.get('/weixin/union/issueCoin2Club',function(req,res){
    router.unionIssueCoin2Club(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("issueCoin2Club 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

//盟主给管理员加联盟币

router.ownerCoin2Admin = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let unionId = req.query.unionId;
    let adminId = req.query.adminId;
    let coinAmount = req.query.coinAmount;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner2(unionId, myuid.uid, res);
    if(!flag){
        res.send({code: 500, msg: '您不是盟主，无权操作'});
        return;
    }

    //判断是不是管理员
    let flag2 = yield router.judgeIsUnionAdministrator2(unionId, adminId, res);
    if(!flag2){
        res.send({code: 500, msg: '管理员不存在'});
        return;
    }

    let log = '盟主(' + myuid.uid + ') 给管理员(' + adminId + ') 加' + coinAmount +'分数';
    yield userDao.qudateUnionAdminCoins(unionId, adminId,coinAmount,log);
    res.send({code:200,msg:"success "});

})

router.get('/weixin/union/ownerCoin2Admin',function(req,res){
    router.ownerCoin2Admin(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("issueCoin2Club 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})


/**
 * 获取联盟未处理的申请信息列表
 * @type {(function(): *)|Function}
 */
router.unionApplyList = P.coroutine(function*(req, res){
    let token = req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner(unionId, myuid.uid, res);
    if(!flag){
        return;
    }
    let applyList = yield userDao.unionApplyList(unionId);
    res.send({code:200, msg:"success", applyList:applyList});
})

router.get('/weixin/union/apply/list', function(req, res){
    router.unionApplyList(req, res).catch(function(e){
        if(!res.finished) {
            console.logw("clubQuitUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})


//获取加入联盟并且加入俱乐部的信息
router.unionAndClubApplyList = P.coroutine(function*(req, res){
    let token = req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);

    //查加入联盟的
    let applyList = yield userDao.unionApplyListById(myuid.uid);
    //查加入俱乐部的
    let clubList = yield clubInfoDao.queryApplyMembers(myuid.uid);
    res.send({code:200, msg:"success", applyList:applyList,clubList:clubList});
})

router.get('/weixin/union/club/applylist', function(req, res){
    router.unionAndClubApplyList(req, res).catch(function(e){
        if(!res.finished) {
            console.logw("clubQuitUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

//是否该显示红点
router.unionAndClubHongdian = P.coroutine(function*(req, res){
    let token = req.query.token;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);

    //查加入联盟的
    let applyList = yield userDao.unionApplyListById(myuid.uid);
    if (applyList && applyList.length > 0){
        res.send({code:200, msg:"success", hongdian:'1'});
        return;
    }
    //查加入俱乐部的
    let clubList = yield clubInfoDao.queryApplyMembers(myuid.uid);
    if(clubList){
        res.send({code:200, msg:"success", hongdian:'1'});
        return;
    }
    res.send({code:200, msg:"success", hongdian:'0'});
})

router.get('/weixin/union/club/applylist/hongdian', function(req, res){
    router.unionAndClubHongdian(req, res).catch(function(e){
        if(!res.finished) {
            console.logw("clubQuitUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})
/**
 * 对联盟内的俱乐部进行启动/冻结操作
 * @type {Function}
 */
router.updateUnionClubState = P.coroutine(function*(req, res){
    let token = req.query.token;
    let clubId = req.query.clubId;
    let unionState = req.query.unionState;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        console.logw('updateUnionClubState club not exist');
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }
    if(!club.unionId){
        console.logw('updateUnionClubState club not in union');
        res.send({code: 500, msg: '俱乐部不在大联盟里'});
        return;
    }

    let myuid = JSON.parse(uid);
    //判断是不是盟主本人操作
    let flag = yield router.judgeIsUnionOwner(club.unionId, myuid.uid, res);
    if(!flag){
        return;
    }
    yield userDao.updateUnionClubState(clubId, unionState);
    res.send({code:200, msg:"success "});
})

router.get('/weixin/union/updateClubState', function(req, res){
    router.updateUnionClubState(req, res).catch(function(e) {
        if(!res.finished) {
            console.logw("updateClubState 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 申请加入联盟
 * @type {Function}
 */
router.clubApplyUnion = P.coroutine(function*(req, res){
    let token = req.query.token;
    let clubId = req.query.clubId;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "用户不存在" });
        return;
    }
    let club = yield userDao.getClubInfoById(clubId);
    if(!club || club.rel === 1){
        console.logw('clubApplyUnion user no right');
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    let union = yield userDao.getUnionById(unionId);
    if(!union){
        console.logw('clubApplyUnion union no exist');
        res.send({code: 500, msg: '联盟不存在'});
        return;
    }


    //判断是否已经加入联盟了
    if(club.unionId != null){
        if(club.unionId !== '' && club != null){
            console.logw('updateUnionClubState club has union already');
            res.send({code: 500, msg: '俱乐部已加入联盟'});
            return;
        }
    }

    //判断是否申请过
    let apply = yield  userDao.getApplyByClubAndUnion(clubId, unionId);
    if(apply && apply.state === 0 ){
        console.logw('updateUnionClubState applied already');
        res.send({code: 500, msg: '已申请过该联盟'});
        return;
    }

    yield userDao.addUnionApply(unionId, clubId);

    //广播
    let member = { msgType:56, unionId:unionId, clubId:clubId, ownerUid:union.ownerUid };
    let s=JSON.stringify(member);
    yield redis.publishUnion(s);

    res.send({code:200,msg:"success "});
})

router.get('/weixin/club/applyUnion', function(req, res){
    router.clubApplyUnion(req, res).catch(function(e){
        if(!res.finished) {
            console.logw("applyUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

//批准/拒绝申请加入联盟
router.handleUnionApply = P.coroutine(function*(req, res){
    let token = req.query.token;
    let unionId = req.query.unionId;
    let clubId = req.query.clubId;
    let state = req.query.state;  //1是批准，2是拒绝

    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    //判断俱乐部是否存在
    let club = yield userDao.getClubInfoById(clubId);
    if(club == null){
        console.logw('俱乐部不存在');
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    //判断是否申请过
    let apply = yield  userDao.getApplyByClubAndUnion(clubId, unionId);
    if(!apply){
        console.logw('handleUnionApply club no apply');
        res.send({code: 500, msg: '用户没申请过该联盟'});
        return;
    }
    yield userDao.handleUnionApply(unionId, clubId, state);
    res.send({code:200,msg:"success "});
})

router.get('/weixin/union/handleApply', function(req, res){
    router.handleUnionApply(req, res).catch(function(e){
        if(!res.finished) {
            console.logw("handleUnionApply 发生异常 "+ e.message);
            res.send({code:500,msg:"exception "});
        }
    });
})

/**
 * 俱乐部退出联盟
 * @type {(function(): *)|Function}
 */
router.clubQuitUnion = P.coroutine(function*(req, res){
    let token = req.query.token;
    let clubId = req.query.clubId;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        console.logw('clubQuitUnion club no exist');
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }
    if(club.unionId == null){
        console.logw('clubQuitUnion club no union');
        res.send({code: 500, msg: '俱乐部不存在联盟'});
        return;
    }
    if (club.ownerUid !== uid) {
        console.logw('不是俱乐部群主，不能进行此操作');
        res.send({code: 500, msg: '不是俱乐部群主，不能进行此操作'});
        return;
    }
    let union = yield userDao.getUnionById(unionId);

    if (club.unionId !== unionId) {
        console.logw('联盟id不正确，不能进行此操作');
        res.send({code: 500, msg: '联盟id不正确，不能进行此操作'});
        return;
    }

    //如果是盟主自己退出大联盟则需要判定该俱乐部是不是盟主的唯一俱乐部
    if(union.ownerUid === uid){
        let able = yield userDao.unionOwnerClubQuitAble(uid, unionId);
        if(!able){
            res.send({code: 500, msg: '盟主至少拥有一个俱乐部在联盟中，不能退出'});
            return;
        }
    }

    yield userDao.clubQuitUnion(clubId,unionId);
    //广播
    let member = { msgType:54, unionId:unionId, clubId:clubId };
    let s=JSON.stringify(member);
    yield redis.publishUnion(s);
    res.send({code:200,msg:"success "});

})

router.get('/weixin/club/quitUnion', function(req, res){
    router.clubQuitUnion(req, res).catch(function(e){
        if(e instanceof BusiError){
            res.send({code:500,msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("clubQuitUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试。"});
        }
    })
})


/**
 * 俱乐部群主发放/减少某成员的疲劳币
 * @type {(function(): *)|Function}
 */
router.clubIssueUnionCoin2Member = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let memberId = req.query.memberId;
    let clubId = req.query.clubId;
    let coinAmount = req.query.coinAmount;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    let myuid = JSON.parse(uid);
    //判断是不是群主本人在操作
    let club = yield  userDao.getClubInfoById(clubId);
    if(!club || club.ownerUid != myuid.uid){
        console.logw('updateUnion user no right');
        res.send({code: 500, msg: '您不是俱乐部群主'});
        return;
    }
    //判断该用户属不属于俱乐部
    let member = yield userDao.getClubMemberById(clubId, memberId);
    if(!member || member.clubId != clubId){
        console.logw('updateUnion club no right');
        res.send({code: 500, msg: '用户不是俱乐部成员'});
        return;
    }

    let myCoin = {
        clubCoin:0,
        memberCoin:0,
    }
    let bool= yield userDao.clubIssueUnionCoin2Member(clubId, memberId, coinAmount,myCoin);
    if(bool){
        let member = { msgType:58, clubCoin:myCoin.clubCoin, memberCoin:myCoin.memberCoin, clubId:clubId, memberId:memberId, ownerId:myuid.uid };
        let s=JSON.stringify(member);
        yield redis.publishUnion(s);
        res.send({code:200,msg:"success "});
    }else{
        res.send({code:500,msg:"俱乐部疲劳币余额不足"});
    }

})

router.get('/weixin/club/issueUnionCoin2Member',function(req,res){
    router.clubIssueUnionCoin2Member(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("issueUnionCoin2Member 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试。"});
        }
    });
})


//获取玩家俱乐部信息
router.clubUserInfo = P.coroutine(function *(req, res) {
    let token = req.query.token;
//    let memberId = req.query.memberId;
    let clubId = req.query.clubId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }
    let myuid = JSON.parse(uid);

    //判断该用户属不属于俱乐部
    let member = yield userDao.getClubMemberById(clubId, myuid.uid);
    if(!member || member.clubId != clubId){
        console.logw('updateUnion club no right');
        res.send({code: 500, msg: '用户不是俱乐部成员'});
        return;
    }
    res.send({code:200,msg:"success", member:member});

})

router.get('/weixin/club/userInfo',function(req,res){
    router.clubUserInfo(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("issueUnionCoin2Member 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试。"});
        }
    });
})

/**
 * 群主获取俱乐部成员列表
 * @type {(function(): *)|Function}
 */
router.clubMemberList = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let clubId = req.query.clubId;
    let onback = req.query.onback;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let memberList = yield userDao.getClubMemberListById(clubId);
    res.send({code:200, msg:"success", memberList:memberList, onback:onback});

})

router.get('/weixin/club/memberList',function(req,res){
    router.clubMemberList(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("clubMemberList 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//俱乐部冻结玩家
router.unionPlayerFrost = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let unionId = req.query.unionId;
    let frostUid = req.query.frostUid;
    let frostType = req.query.frostType;//1 冻结 2 解冻
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "invalid uid" });
        return;
    }

    let myuid = JSON.parse(uid);

    //是否管理员
    let flag = yield router.judgeIsUnionAdministrator(unionId, myuid.uid, res);
    if(!flag){
        res.send({ code: 500, msg:"不是管理员，不能此操作" });
        return;
    }
    //冻结玩家
    let flag2 = yield userDao.frostPlayer(unionId,frostUid,frostType);
    if(!flag2){
        res.send({ code: 500, msg:"玩家不存在" });
        return;
    }
    //广播
    let member = { msgType:53, unionId:unionId, player:frostUid, frostType:frostType };
    let s=JSON.stringify(member);
    yield redis.publishUnion(s);

    res.send({ code: 200, msg:"success " });

})

router.get('/weixin/union/player/frost',function(req,res){
    router.unionPlayerFrost(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("unionPlayerFrost 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});



/**
 * 获取联盟的的疲劳值发放记录
 */
router.unionCoinRecordList = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "用户无权限" });
        return;
    }

    let unionRecordList = yield userDao.unionCoinRecordList(unionId);
    let clubRecordList = yield userDao.unionClubCoinRecordList(unionId);
    res.send({code:200, msg:"success", unionRecordList: unionRecordList, clubRecordList: clubRecordList});
})

router.get('/weixin/union/coin/recordList',function(req,res){
    router.unionCoinRecordList(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("clubMemberList 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

/**
 * 获取俱乐部的疲劳值发放记录
 */
router.clubUnionRecordList = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let clubId = req.query.clubId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "用户无权限" });
        return;
    }
    let club = yield  userDao.getClubInfoById(clubId);
    if(!club){
        res.send({code: 500, msg: "俱乐部不存在"});
        return;
    }



    let recordList = yield userDao.clubUnionRecordList(clubId);
    res.send({code:200, msg:"success", recordList:recordList});

})

router.get('/weixin/club/ucoin/recordList',function(req,res){
    router.clubUnionRecordList(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("clubMemberList 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});


/**
 * 获取俱乐部的疲劳值
 */
router.clubUnion = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let clubId = req.query.clubId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "用户无权限" });
        return;
    }
    let club = yield  userDao.getClubInfoById(clubId);
    if(!club){
        res.send({code: 500, msg: "俱乐部不存在"});
        return;
    }
    res.send({code:200, msg:"success", unionCoin: club.unionCoin});

});

router.get('/weixin/club/ucoin',function(req,res){
    router.clubUnion(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("clubMemberList 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

router.getFrostPlayerList = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, err: "用户无权限" });
        return;
    }
    //是否管理员
    let flag = yield router.judgeIsUnionAdministrator(unionId, uid, res);
    if(!flag){
        return;
    }
    //冻结玩家
    let playerList = yield userDao.listUnionFrostPlayer(unionId);

    res.send({code:200, msg:"success", playerList: playerList});

});

router.get('/weixin/union/frostPlayerList',function(req,res){
    router.getFrostPlayerList(req,res).catch(function(e) {
        if(!res.finished) {
            console.logw("getFrostPlayerList 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

router.dissolveUnion = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let unionId = req.query.unionId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }
    //判断是不是盟主本人在操作
    let flag = yield router.judgeIsUnionOwner(unionId, uid, res);
    if(!flag){
        return;
    }
    //解散大联盟
    yield userDao.dissolveUnion(unionId);

    res.send({code:200, msg:"success"});

});

router.get('/weixin/union/dissolve',function(req,res){
    router.dissolveUnion(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("dissolveUnion 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//获取俱乐部信息
router.getClubInfo = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let clubId = req.query.clubId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let clubMember = yield clubMemberDao.getByUIDJoin(clubId);
    if(!clubMember){
        throw new BusiError(500, "获取俱乐部信息失败");
    }
    res.send({code:200, msg:"success",clubinfo:clubMember});

});

router.get('/weixin/club/getclubinfo',function(req,res){
    router.getClubInfo(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===============================================================================================

//EventTypeQueryClubRooms         EventType = 3  // 查询俱乐部房间事件
router.eventTypeQueryClubRooms = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let clubId = req.query.clubId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let clubMember = yield clubMemberDao.getByUIDJoin(clubId);
    if(!clubMember){
        throw new BusiError("获取俱乐部信息失败");
    }
    gameService.queryClubRoom(clubId).then(res2 => {
        res.send({code: 200, msg: "success", data: res2,clubInfo:clubMember});
    }).catch(err => {
        console.logw("query club room err:", err.message);
        throw new BusiError(err);
    });
});
router.get('/weixin/club/eventTypeQueryClubRooms',function(req,res){
    router.eventTypeQueryClubRooms(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});
//========================================================================================

//EventTypeCreateClub             EventType = 4  // 创建俱乐部事件
// eslint-disable-next-line require-yield
router.eventTypeCreateClub = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let clubName = req.query.clubName;
    clubMemberService.createClub(uid, clubName).then(res2 => {
        let result = {};
        result.code = 200;
        result.msg = "success";
        result.data = res2;
        res.send(result);
    }).catch(e => {
        let msg = "创建俱乐部失败";
        if (e instanceof BusiError) {
            msg = e.message;
        }
        res.send({ code: 500, msg: msg });
    });
});

router.get('/weixin/club/eventTypeCreateClub',function(req,res){
    router.eventTypeCreateClub(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//======================================================================================================
//EventTypeRenameClub             EventType = 5  // 重命名俱乐部事件
// eslint-disable-next-line require-yield
router.eventTypeRenameClub = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let clubId = req.query.clubId;
    let uid = -1;
    try {
        uid = Token.aesDecodeDef(token);
        if (uid == null) uid = -1;
        if (typeof uid === "string") {
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({code: 500, msg: "用户无权限"});
        return;
    }

    let clubName = req.query.clubName;
    let club_info = yield clubInfoDao.getByName(clubName);
    if (club_info) {
        throw new BusiError(500, "俱乐部名字已存在");
    }

    let club = yield userDao.getClubInfoById(clubId);
    if (club == null) {
        throw new BusiError(500, "俱乐部不存在");
    }
    if (club.ownerUid != uid) {
        throw new BusiError(500, "不是群主，不能进行此操作");
    }
    let resClubInfoName = yield clubInfoDao.updateClubInfoName(clubName,clubId,uid);
    if(resClubInfoName == null){
        throw new BusiError(500, "重命名俱乐部失败1");
    }
    let resClubName = yield clubInfoDao.updateClubName(clubName,clubId,uid);
    if(resClubName == null){
        throw new BusiError(500, "重命名俱乐部失败2");
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = clubName;
    res.send(result);
});

router.get('/weixin/club/eventTypeRenameClub',function(req,res){
    router.eventTypeRenameClub(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===================================================================================================
//EventTypeReleaseClub            EventType = 7  // 解散俱乐部事件

// eslint-disable-next-line require-yield
router.eventTypeReleaseClub = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club =yield userDao.getClubInfoById(clubId);
    if(club == null){
        throw new BusiError(500, "俱乐部不存在");
    }

    clubMemberService.dissolveClub(uid, clubId).then(res2 => {
        let result = {};
        result.code = 200;
        result.msg = "success";
        result.data = res2;
        res.send(result);
    }).catch(e => {
        let msg = "解散俱乐部失败";
        if (e instanceof BusiError) {
            msg = e.message;
        }
        res.send({ code: 500, msg: msg });
    });

});
router.get('/weixin/club/eventTypeReleaseClub',function(req,res){
    router.eventTypeReleaseClub(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===================================================================================
//EventTypeClubSetting            EventType = 8  // 俱乐部设置事件

// eslint-disable-next-line require-yield
router.eventTypeClubSetting = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let setting = req.query.setting;
    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club =yield userDao.getClubInfoById(clubId);
    if(club == null){
        throw new BusiError(500, "俱乐部不存在");
    }

    if (club.ownerUid != uid) {
        throw new BusiError(500, "设置失败, 不是群主不能设置");
    }

    let resInfoClubSetting = yield clubInfoDao.updateInfoSettingByID(setting,clubId,uid);
    if(resInfoClubSetting == null){
        throw new BusiError(500, "设置俱乐部失败1");
    }

    let resClubSetting = yield clubInfoDao.updateSettingByID(setting,clubId,uid);
    if(resClubSetting == null){
        throw new BusiError(500, "设置俱乐部失败2");
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = setting;
    res.send(result);

});

router.get('/weixin/club/eventTypeClubSetting',function(req,res){
    router.eventTypeClubSetting(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=================================================================================================
//EventTypeCreateClubRoom         EventType = 9  // 创建俱乐部房间事件

// eslint-disable-next-line require-yield
router.eventTypeCreateClubRoom = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let resDate = "";
    gameService.createFkGameRoom(uid, req.body.gt, clubId, req.body.data).then(res2 => {
        resDate = res2;
    }).catch(err => {
        throw new BusiError(err);
    });

    let resClub = yield clubInfoDao.queryMemberUIDByID(clubId);

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = resDate;
    result.uids = resClub;
    res.send(result);

});

router.get('/weixin/club/eventTypeCreateClubRoom',function(req,res){
    router.eventTypeCreateClubRoom(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=================================================================================================
//EventTypeJoinClub               EventType = 10 // 加入俱乐部事件

// eslint-disable-next-line require-yield
router.eventTypeJoinClub = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club =yield userDao.getClubInfoById(clubId);
    if(club == null){
        throw new BusiError("俱乐部不存在");
    }

    let member =yield clubInfoDao.getByMemberUID(uid,clubId);
    if(member != null){
        if (member.Agree == 0) {//初始化
            let result = {};
            result.code = 200;
            result.msg = "success";
            result.data = member;
            res.send(result);
            return;
        }else if (member.Agree == 1) {
            res.send({ code: 500, msg: "申请已经通过, 无需再次申请" });
            return;
        }else if (member.Agree == -2) {
            res.send({ code: 500, msg: "加入俱乐部失败, 已被屏蔽" });
            return;
        }else if (member.Agree == -1 || member.Agree == -3) {
            let status =yield clubInfoDao.updateStatusByID(0,member.ID);
            if (status == null){
                res.send({ code: 500, msg: "加入俱乐部失败, 请稍后再试" });
                return;
            }
            member.Agree = 0;
            let result = {};
            result.code = 200;
            result.msg = "success";
            result.data = member;
            res.send(result);
            return;
        }

        res.send({ code: 500, msg: "加入俱乐部失败" });
        return;

    }else{
        //创建一条加入信息
    }

});

router.get('/weixin/club/eventTypeJoinClub',function(req,res){
    router.eventTypeJoinClub(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//======================================================================================
//EventTypeQueryClubs             EventType = 11 // 查询俱乐部列表事件

// eslint-disable-next-line require-yield
router.eventTypeQueryClubs = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let resMen =yield clubInfoDao.queryMembersByUID2(uid);
    if(resMen == null){
        res.send({ code: 500, msg: "用户没有俱乐部" });
    }

//    GetClubCntInfo
    let sendmap = [];
    for(let i = 0; i < resMen.length; i++){
        let ci = resMen[i];
        let obj = {
            ClubInfo:ci,
            roomCnt:0,
            memberCnt:0,
        };
        yield roomCacheService.GetClubCntInfo(ci.clubId,obj);
        sendmap.push(obj);
    }
    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = sendmap;
    res.send(result);
});

router.get('/weixin/club/eventTypeQueryClubs',function(req,res){
    router.eventTypeQueryClubs(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//============================================================================
//EventTypeGetClub                EventType = 12 // 通过俱乐部ID查询俱乐部事件

// eslint-disable-next-line require-yield
router.eventTypeGetClub = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    //获取俱乐部信息
    //    GetClubCntInfo
    //返回
    let obj = {
        ClubInfo:club,
        roomCnt:0,
        memberCnt:0,
    };
    yield roomCacheService.GetClubCntInfo(clubId,obj);
    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = obj;
    res.send(result);

});

router.get('/weixin/club/eventTypeGetClub',function(req,res){
    router.eventTypeGetClub(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===================================================================================
//EventTypeRemoveClubMember       EventType = 13 // 移除俱乐部成员事件

// eslint-disable-next-line require-yield
router.eventTypeRemoveClubMember = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberId = req.query.memberId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let member =yield clubInfoDao.getByMemberUID(memberId,clubId);
    if(member == null){
        res.send({ code: 500, msg: "处理失败, 请稍后再试" });
        return;
    }

    if (member.ownerUid != uid) {
        res.send({ code: 500, msg: "处理失败, 你无权操作" });
        return;
    }

    if (member.ownerUid == member.memberUid) {
        res.send({ code: 500, msg: "处理失败, 自己不能刪除自己" });
        return;
    }

    if (member.coins != 0) {
        res.send({ code: 500, msg: "处理失败, 成员的金币豆没有清零" });
        return;
    }
    if (member.unionCoin != 0) {
        res.send({ code: 500, msg: "处理失败, 成员的疲劳值没有清零" });
        return;
    }

    let update =yield clubInfoDao.updateClubMemberByID(clubId,member.memberUid);
    if(update == null){
        res.send({ code: 500, msg: "删除处理失败, 请稍后再试" });
        return;
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    res.send(result);
    return;
});

router.get('/weixin/club/eventTypeRemoveClubMember',function(req,res){
    router.eventTypeRemoveClubMember(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//======================================================================================================
//EventTypeQueryClubMembers       EventType = 14 // 查询俱乐部成员列表事件

router.eventTypeQueryClubMembers = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }
//
    let query =yield clubInfoDao.queryMembersByID(clubId);
    if(query == null){
        res.send({ code: 500, msg: "查询俱乐部成员列表处理失败, 请稍后再试" });
        return;
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = query;
    res.send(result);
    return;

});


router.get('/weixin/club/eventTypeQueryClubMembers',function(req,res){
    router.eventTypeQueryClubMembers(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===============================================================================================================
//EventTypeApplyClubProcess       EventType = 16 // 申请加入俱乐部处理事件

router.eventTypeApplyClubProcess = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    if (club.OwnerUID != uid) {
        res.send({code: 500, msg: '俱乐部归属者有误'});
        return;
    }

    let member =yield clubInfoDao.getByMemberUID(uid,clubId);
    if(member == null){
        res.send({code: 500, msg: '处理失败'});
        return;
    }

    if (member.Agree != 0) {
        res.send({code: 500, msg: '该申请已经处理过'});
        return;
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = member;
    res.send(result);
    return;

});

router.get('/weixin/club/eventTypeApplyClubProcess',function(req,res){
    router.eventTypeApplyClubProcess(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===================================================================
//EventTypeReleaseClubNotify      EventType = 17 // 解散俱乐部通知事件

router.eventTypeReleaseClubNotify = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    if (club.OwnerUID != uid) {
        res.send({code: 500, msg: '俱乐部归属者有误'});
        return;
    }

    let member =yield clubInfoDao.getByMemberUID(uid,clubId);
    if(member == null){
        res.send({code: 500, msg: '处理失败'});
        return;
    }

    if (member.Agree != 0) {
        res.send({code: 500, msg: '该申请已经处理过'});
        return;
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = member;
    res.send(result);
    return;

});

router.get('/weixin/club/eventTypeReleaseClubNotify',function(req,res){
    router.eventTypeReleaseClubNotify(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//==============================================================
//EventTypeAddClubMemberCoins     EventType = 18 // 给俱乐部成员上分事件 addCoinsByMemberUID(coins,clubId,ownerUid,memberUid)

router.eventTypeAddClubMemberCoins = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let coins = req.query.coins;
//    let ownerUid = req.query.ownerUid;
    let memberUid = req.query.memberUid;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let resCoins = yield clubInfoDao.addCoinsByMemberUID(coins,clubId,uid,memberUid);
    if(!resCoins){
        res.send({code: 500, msg: '给成员加金币失败'});
        return;
    }

    //保存记录
    let order = {
        club_id: clubId,
        m_uid: uid,
        o_uid: memberUid,
        coins: coins,
        remark: "群主操作",
    };
    let saveOrderId = yield clubCoinsUpdateRecordDao.save(order);
    if (saveOrderId <= 0) {
        console.logw("给成员加金币保存记录失败 uid=" + uid);
        res.send({code: 500, msg: '给成员加金币保存记录失败 uid=' + uid });
        return;
    }

    //返回消息
    let member =yield clubInfoDao.getByMemberUID(memberUid,clubId);
    if(member == null){
        res.send({ code: 500, msg: "处理失败, 请稍后再试" });
        return;
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = member;
    res.send(result);
});


router.get('/weixin/club/eventTypeAddClubMemberCoins',function(req,res){
    router.eventTypeAddClubMemberCoins(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===============================================================================
//EventTypeQuickJoinClubRoom      EventType = 19 // 快速加入俱乐部房间事件

router.eventTypeQuickJoinClubRoom = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let member =yield clubInfoDao.getByMemberUID(uid,clubId);
    if(member == null){
        res.send({ code: 500, msg: "处理失败, 请稍后再试" });
        return;
    }

    gameService.joinClubRoom(clubId).then(res2 => {
        res.send({code: 200, msg: "success", data: res2});
    }).catch(err => {
        throw new BusiError(err);
    });

});

router.get('/weixin/club/eventTypeQuickJoinClubRoom',function(req,res){
    router.eventTypeQuickJoinClubRoom(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===============================================================================
//EventTypeLeaveClub              EventType = 20 // 离开俱乐部房间事件

router.eventTypeLeaveClub = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    //如果是群主，解散俱乐部
    if(club.ownerUid == uid){
        clubMemberService.dissolveClub(uid, clubId).then(res2 => {
            res.send({code: 200, msg: "success"});
        }).catch(e => {
            res.send({code: 500, msg: "分数未结清，无法解散俱乐部"});
            return;
        });
    }

    //离开俱乐部
    clubMemberService.quitClub(uid, clubId).then(res3 => {
        res.send({code: 200, msg: "success"});
    }).catch(e => {
        res.send({code: 500, msg: "分数未结清，无法退出俱乐部"});
        return;
    });
});

router.get('/weixin/club/eventTypeLeaveClub',function(req,res){
    router.eventTypeLeaveClub(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//==================================================================
//EventTypeAgreeClubMember        EventType = 21 // 同意加入俱乐部

router.eventTypeAgreeClubMember = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberUid = req.query.memberUid;
    let agree = req.query.agree;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let member =yield clubInfoDao.getByMemberUID(memberUid,clubId);
    if(member == null){
        res.send({ code: 500, msg: "处理失败, 请稍后再试" });
        return;
    }

    let update =yield clubInfoDao.updateClubMemberByIDAgree(member.memberUid,clubId,agree);
    if(update == null){
        res.send({ code: 500, msg: "删除处理失败, 请稍后再试" });
        return;
    }
    res.send({ code: 200, msg: "success" });
//   member.Agree =


});

router.get('/weixin/club/eventTypeAgreeClubMember',function(req,res){
    router.eventTypeAgreeClubMember(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//======================================================================================
//EventTypeQueryApplyMembers      EventType = 22 // 查询俱乐部申请消息事件

router.eventTypeQueryApplyMembers = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }


    let query =yield clubInfoDao.queryApplyMembersByID(uid,clubId);
    if(query == null){
        res.send({ code: 500, msg: "查询俱乐部申请消息失败, 请稍后再试" });
        return;
    }

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = query;
    res.send(result);
    return;

});

router.get('/weixin/club/eventTypeQueryApplyMembers',function(req,res){
    router.eventTypeQueryApplyMembers(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=======================================================================================
//EventTypeUpdateClubMemberBuffer EventType = 23 // 更新buffer事件

router.eventTypeUpdateClubMemberBuffer = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let buffer = req.query.buffer;
    let memberUid = req.query.memberUid;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let memberUser = yield userDao.getUserByUid(uid);
    if(memberUser == null){
        res.send({code:500,msg:"用户不存在"});
        return;
    }

    let update2 =yield clubInfoDao.updateBuffer(-buffer,uid);
    if(update2 == null){
        res.send({ code: 500, msg: "更新buffer失败, 请稍后再试" });
        return;
    }

    let update =yield clubInfoDao.updateBufferByMemberUID(buffer,clubId,uid,memberUid);
    if(update == null){
        res.send({ code: 500, msg: "更新buffer失败, 请稍后再试" });
        return;
    }

});

router.get('/weixin/club/eventTypeUpdateClubMemberBuffer',function(req,res){
    router.eventTypeUpdateClubMemberBuffer(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===========================================================================================================
//EventTypeUpdateClubCards        EventType = 24 // 更新基金事件

router.eventTypeUpdateClubCards = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let cards = req.query.cards;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        console.logw("俱乐部不存在 uid=" + uid);
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    let resData = yield userDao.getUserByIdAsync(uid);
    if (!resData) {
        console.logw("玩家信息不存在 uid=" + uid);
        res.send({ code: 500, msg: '玩家信息不存在' });
        return;
    }

    // if(club.chargeMode == 1){
    //     if(uid != club.ownerUid){
    //        // return nil, errors.New("操作失败, 该俱乐部只允许群主充值基金")
    //         res.send({code: 500, msg: '操作失败, 该俱乐部只允许群主充值基金'});
    //     }
    // }

    if (resData.cardNum < cards){
        console.logw("房卡操作失败 uid=" + uid);
        res.send({code: 500, msg: '房卡不足'});
        return;
    }

    let decCardRes = yield clubInfoDao.upateCards(clubId, cards);
    if (decCardRes <= 0) {
        console.logw("房卡操作失败 uid=" + uid);
        res.send({code: 500, msg: '房卡操作失败'});
        return;
    }

    let decCardRes2 = yield userDao.decCardKou(uid, cards);
    if (decCardRes2 <= 0) {
        console.logw("房卡操作失败2 uid=" + uid);
        res.send({code: 500, msg: '房卡操作失败2'});
        return;
    }

    //记录操作
    let order = {
        clubId: clubId,
        cards: cards,
        uid: uid,
        type: "CLUB_UPDATE",
        remark: "俱乐部充值",
        name: resData.name,
        headimgurl: resData.headimgurl,
    };

    let saveOrderId = yield clubCardsUpdateRecordDao.save(order);
    if (saveOrderId <= 0) {
        console.logw("房卡操作保存记录失败 uid=" + uid);
        res.send({code: 500, msg: '房卡操作保存记录失败 uid=' + uid });
        return;
    }

    club.clubCard = club.clubCard + cards;
    let resClub = yield clubInfoDao.queryMemberUIDByID(clubId);
    let result = {};
    result.code = 200;
    result.msg = "success";
   result.club = club;
    result.uids = resClub;
    res.send(result);

});

router.get('/weixin/club/eventTypeUpdateClubCards',function(req,res){
    router.eventTypeUpdateClubCards(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===============================================================================================
//EventTypeGetClubCards           EventType = 25 // 获取基金事件

router.eventTypeGetClubCards = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let club = yield userDao.getClubInfoById(clubId);
    if(!club){
        res.send({code: 500, msg: '俱乐部不存在'});
        return;
    }

    let obj = {
        ClubInfo:club,
        roomCnt:0,
        memberCnt:0,
    };
    yield roomCacheService.GetClubCntInfo(clubId,obj);
    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = obj;
    res.send(result);

});


router.get('/weixin/club/eventTypeGetClubCards',function(req,res){
    router.eventTypeGetClubCards(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=============================================================================================
//EventTypeQueryUnionRooms EventType = 50 // 查询大联盟房间事件

router.eventTypeQueryUnionRooms = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let unionID= req.body.unionID;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let member =yield clubInfoDao.getByMemberUID(uid,clubId);
    if(member == null){
        res.send({ code: 500, msg: "处理失败, 请稍后再试" });
        return;
    }

    gameService.queryUnionRoom(unionID).then(res2 => {
 //       resp.send({code: 200, msg: "success", data: res});
    }).catch(err => {
        // console.logw("query club room err:", err.message);
        // resp.send(new ErrorResult(err));
    });

});


router.get('/weixin/club/eventTypeQueryUnionRooms',function(req,res){
    router.eventTypeQueryUnionRooms(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===============================================================================================
//EventTypeCreateUnionRoom EventType = 51 // 创建大联盟房间事件

router.eventTypeCreateUnionRoom = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let unionID= req.body.unionID;
    let gt = req.body.gt;
    let data = req.body.data;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }


    if(!gt || gt === '') {
        res.send({code: 500, msg: "game type is null"});
        return;
    }

    if(!data || data === '') {
        res.send({code: 500, msg: "data is null"});
        return;
    }

    gameService.createUnionGameRoom(uid, gt, unionID, data).then(res => {
        //add
        let mymap = {};
        mymap.uid = req.uid;
        mymap.gt = req.body.gt;
        mymap.unionID = req.body.unionID;
        mymap.data = req.body.data;
        mymap.roomid = res.roomID;
        mymap.ts = res.ts;

        let key = mymap.gt + mymap.roomid + mymap.ts;

        // unionRoomMap[key] = mymap;
        //
        // resp.send({code: 200, msg: "success", data: res});
    }).catch(err => {
        // console.logw("game create err:", err.message);
        // resp.send(new ErrorResult(err));
    });

});

router.get('/weixin/club/eventTypeCreateUnionRoom',function(req,res){
    router.eventTypeCreateUnionRoom(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//========================================================================================
//以下是大联盟代理相关

//会员查询
router.agnetGetMyMenberInfo = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let pageNo = parseInt(req.query.pageNo);
    let memberId = req.query.memberId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //获取盟主信息
    let resMaster = null;
    let resmz = null;
    let resMy;
    if(!memberId){
        resmz =yield agentService.getMasterMemberInfo(clubId);
        if (resmz == null){
            res.send({ code: 500, msg: "盟主信息不存在" });
            return;
        }

        let resLd =yield agentService.getLeaderUid(clubId,uid);
        if(resLd){
            let myId = resLd.agentLeader;
            resMaster =yield agentService.getPlayerMemberInfo(clubId,myId);
        }
        //获取自己信息
        resMy=yield agentService.getPlayerMemberInfo(clubId,uid);
        if (resMy == null){
            res.send({ code: 500, msg: "自己信息不存在" });
            return;
        }
    }

    //其他会员信息
    let resMember;
    if(memberId){
        resMember = yield agentService.getMyMemberInfoOne(clubId,uid,memberId);
    }else{
        resMember = yield agentService.getMyMemberInfo(clubId,uid,pageNo);
    }



    let result = {};
    result.code = 200;
    result.msg = "success";
    result.resmz = resmz;//盟主信息
    result.master = resMaster;
    result.my = resMy;
    result.member = resMember;
    res.send(result);

});

router.get('/weixin/agent/agnetGetMyMenberInfo',function(req,res){
    router.agnetGetMyMenberInfo(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});
//=======================================================================================
//会员详细
router.agnetGetMenberXiangxi = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberId = req.query.memberId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //获取税收

    //昨日税收
    let yTax = yield agentService.getMyTaxAll(clubId,memberId,1);
    //今日税收
    let dTax = yield agentService.getMyTaxAll(clubId,memberId,0);

    //获取新增会员
    let dNum = yield agentService.getMyNewMenberNum(clubId,memberId,0);
    let yNum = yield agentService.getMyNewMenberNum(clubId,memberId,1);
    //直属会员数目
    let mNum = yield agentService.getMyMenberNum(clubId,memberId);

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.dNum = dNum;
    result.yNum = yNum;
    result.mNum = mNum;
    result.dTax = dTax;
    result.yTax = yTax;
    res.send(result);

});

router.get('/weixin/agent/agnetGetMenberXiangxi',function(req,res){
    router.agnetGetMenberXiangxi(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=====================================================================================================
//编辑合伙人
router.agnetChangePartnerYield = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberId = req.query.memberId;
    let MyYield = req.query.myYield;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //获取合伙人原来的抽成
    //获取盟主信息
    let resMember =yield agentService.getUserYield(clubId,memberId);
    if (resMember == null){
        res.send({ code: 500, msg: "合伙人信息不存在" });
        return;
    }
    if(resMember.agentLeader != uid){
        res.send({ code: 500, msg: "该玩家不是你的合伙人" });
        return;
    }
    //获取我的抽成
    let resMy =yield agentService.getUserYield(clubId,uid);
    if (resMy == null){
        res.send({ code: 500, msg: "本人信息不存在" });
        return;
    }
    //符合条件修改，不符合返回错误
    if(!resMember.agentYield || !resMy.agentYield){
        res.send({ code: 500, msg: "分成信息为空" });
        return;
    }

    if(MyYield <= resMember.agentYield || MyYield >= resMy.agentYield){
        res.send({ code: 500, msg: "设置分数不符合范围" });
        return;
    }
    //修改合伙人收益
    yield agentService.changeUserYield(clubId,memberId,MyYield);

    let result = {};
    result.code = 200;
    result.msg = "success";
    res.send(result);
});

router.get('/weixin/agent/agnetChangePartnerYield',function(req,res){
    router.agnetChangePartnerYield(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===============================================================================================
//合伙人列表
router.agnetGetPartnerList = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberId = req.query.memberId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //获取列表
    let resMy =yield agentService.getMyUserList(clubId,memberId);

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = resMy;
    res.send(result);
});

router.get('/weixin/agent/agnetGetPartnerList',function(req,res){
    router.agnetGetPartnerList(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===================================================================================
//设置合伙人
router.agnetSetPartner = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberId = req.query.memberId;
    let myYield = req.query.myYield;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //判断分成是否符合条件
    let resMy =yield agentService.getUserYield(clubId,uid);
    if (resMy == null){
        res.send({ code: 500, msg: "本人信息不存在" });
        return;
    }

    //符合条件修改，不符合返回错误
    if(!resMy.agentYield){
        res.send({ code: 500, msg: "分成信息为空" });
        return;
    }

    if(myYield >= resMy.agentYield || myYield < 1){
        res.send({ code: 500, msg: "设置分数不符合范围" });
        return;
    }

    //判断是否直属会员以及是否已经是合伙人
    let bl = yield agentService.isMyDirectMenber(clubId,uid,memberId);
    if(!bl){
        res.send({ code: 500, msg: "玩家不是您的直属会员或已经有了合伙人" });
        return;
    }
    //升级合伙人
    yield agentService.setPartner(clubId,uid,memberId,myYield);
    //表同时也要升级
    yield agentService.setPartnerTable(clubId,memberId);

    let result = {};
    result.code = 200;
    result.msg = "success";
    res.send(result);
});

router.get('/weixin/agent/agnetSetPartner',function(req,res){
    router.agnetSetPartner(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//============================================================================================
//转账
router.agnetTransfer = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberId = req.query.memberId;
    let score = req.query.score;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //获取自己分数

    let resMy =yield agentService.getUserCions(clubId,uid);
    if (resMy == null){
        res.send({ code: 500, msg: "本人信息不存在" });
        return;
    }
    let myScore = resMy.coins;
    myScore = myScore - 3;
    if(myScore < score){
        res.send({ code: 500, msg: "分数不够转账" });
        return;
    }
    //获取玩家的
    let resMember =yield agentService.getUserCions(clubId,memberId);
    if (resMember == null){
        res.send({ code: 500, msg: "玩家信息不存在" });
        return;
    }
    //自己减分
    yield agentService.updateUserCions(clubId,uid,-score);
    //玩家加分
    yield agentService.updateUserCions(clubId,memberId,score);
    //添加转账列表
    yield agentService.infoUserTransfer(clubId,uid,memberId,score);

    let result = {};
    result.code = 200;
    result.msg = "success";
    res.send(result);
});

router.get('/weixin/agent/agnetTransfer',function(req,res){
    router.agnetTransfer(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//==============================================================================
//转账账单
router.agnetBill = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let memberId = req.query.memberId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //判断是否查询一个人还是全部
    if(memberId){
 //      async getMyBillToOne(clubId,uid,memberId) {
        let res1 =yield agentService.getMyBillToOne(clubId,uid,memberId);
        let result1 = {};
        result1.code = 200;
        result1.msg = "success";
        result1.data = res1;
        res.send(result1);
        return;
    }

    let res2 =yield agentService.getMyBill(clubId,uid);
    let result2 = {};
    result2.code = 200;
    result2.msg = "success";
    result2.data = res2;
    res.send(result2);

});

router.get('/weixin/agent/agnetBill',function(req,res){
    router.agnetBill(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//====================================================================================
//报表 要推敲一下

router.agnetGetStatement = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let myMonth = req.query.myMonth; // 0：今月 1：上月 2：上上月

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let resS =yield agentService.getMyStatement(clubId,uid,myMonth);

    let result = {};
    result.code = 200;
    result.msg = "success";
    result.month = resS;
    res.send(result);

});

router.get('/weixin/agent/agnetGetStatement',function(req,res){
    router.agnetGetStatement(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=========================================================================================
//获取直属合伙人报表
router.agnetGetPartnerStatement = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
 //   let myMonth = req.query.myMonth; // 0：今月 1：上月 2：上上月
    let tsDate = req.query.tsDate;      //日期
    let partner = req.query.partner; // 0：会员查询 1：合伙人查询

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let resS;
    if(partner == 1){
        resS=yield agentService.getMyPartnerStatement(clubId,uid,tsDate);
    }else{
        resS=yield agentService.getMyMenberStatement(clubId,uid,tsDate);
    }


    let result = {};
    result.code = 200;
    result.msg = "success";
    result.month = resS;
    res.send(result);

});

router.get('/weixin/agent/agnetGetPartnerStatement',function(req,res){
    router.agnetGetPartnerStatement(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//====================================================================================
//报表的相关数据 今日税收 当月总税收 当月总收益

router.getAllMyInfo = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let resA =yield agentService.getMyStatementAll(clubId,uid);
    let resD =yield agentService.getMyTaxAll(clubId,uid,0);
    let result = {};
    result.code = 200;
    result.msg = "success";
    if(!resA){
        result.allTax = 0;
        result.allScore = 0;
    }else{
        if(resA['sum(tax)'] == null){
            result.allTax = 0;
        }else{
            result.allTax = resA['sum(tax)'];
        }

        if(resA['sum(meScore)'] == null){
            result.allScore = 0;
        }else{
            result.allScore = resA['sum(meScore)'];
        }
    }

    result.day = resD;
    res.send(result);

});

router.get('/weixin/agent/getAllMyInfo',function(req,res){
    router.getAllMyInfo(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=====================================================================================
//上级名片

router.getAgentLeader = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //先获取上级信息
    let resLd =yield agentService.getLeaderUid(clubId,uid);
    if(!resLd){
        res.send({ code: 500, msg: "本人信息不存在" });
        return;
    }
    let myId = '0';
    if(!resLd.agentLeader || resLd.agentLeader == 0){
        //自己是盟主本人
        myId = uid;
    }else{
        myId = resLd.agentLeader;
    }
    //获取自己的邀请码
 //   let yqcCode = uid + clubId;
    let yqcCode = uid;

    //获取信息
    let res2 =yield agentService.getPlayerMemberInfo(clubId,myId);
    let ldCard =yield agentService.getMyCard(clubId,myId);
    let result2 = {};
    result2.code = 200;
    result2.msg = "success";
    result2.data = res2;
    result2.ldCard = ldCard;
    result2.yqcCode = yqcCode;
    res.send(result2);

});

router.get('/weixin/agent/getAgentLeader',function(req,res){
    router.getAgentLeader(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//======================================================================================
//邀请码
router.useCodeInto = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let code = req.query.code;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    //获取自己的邀请码
    // if (code.length < 6){
    //     res.send({ code: 500, msg: "错误的邀请码" });
    //     return;
    // }
    // let codeUid = code.substring(0,6);
    // let codeClubId = code.substring(6,code.length);
    // if(!codeClubId){
    //     res.send({ code: 500, msg: "错误的邀请码2" });
    //     return;
    // }

    let codeUid = code;
    let codeClubId = '5740934';

    let resLd =yield agentService.getUserYield(codeClubId,codeUid);
    if (resLd == null){
        res.send({ code: 500, msg: "邀请者不存在" });
        return;
    }

    let clubinfo =yield clubMemberService.agentJoinClub(uid, codeUid, resLd.agentLevel + 1,codeClubId);

    //记录会员表
    yield agentService.addMember(codeClubId,uid,codeUid,1,0);
    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = clubinfo;
    res.send(result);

});

router.get('/weixin/agent/useCodeInto',function(req,res){
    router.useCodeInto(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//===================================================================
//判断玩家是否在代理大联盟里边

router.playerInAgent = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let clubinfo =yield agentService.IsInAgent(clubId,uid);
    let clubPlayerNum = yield agentService.getAgetnClubAllNum(clubId);
    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = clubinfo;
    result.num = clubPlayerNum;
    res.send(result);

});


router.get('/weixin/agent/playerInAgent',function(req,res){
    router.playerInAgent(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=========================================================================================
//玩家名片
router.getUserCard = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

//    let yqmCode = uid + clubId;
    let yqmCode = uid;

    let myCard =yield agentService.getMyCard(clubId,uid);
    let result = {};
    result.code = 200;
    result.msg = "success";
    result.data = myCard;
    result.yqmCode = yqmCode;
    res.send(result);

});
router.get('/weixin/agent/getUserCard',function(req,res){
    router.getUserCard(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//=======================================================
//设置名片

router.setUserCard = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;
    let qq = req.query.qq;
    let wx = req.query.wx;
    let xl = req.query.xl;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let myCard =yield agentService.setMyCard(clubId,uid,qq,wx,xl);
    let result = {};
    result.code = 200;
    result.msg = "success";
    res.send(result);

});

router.get('/weixin/agent/setUserCard',function(req,res){
    router.setUserCard(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});

//==========================================================================
//获取总人数信息

router.getAllPlayerNum = P.coroutine(function *(req, res) {
    let token = req.query.token;
    let uid = -1;
    let clubId = req.query.clubId;

    try {
        uid = Token.aesDecodeDef(token); if (uid == null) uid = -1;
        if(typeof uid === "string"){
            uid = JSON.parse(uid).uid;
        }
    } catch (e) {
        console.logw('decode token failed ', token, 'uid', uid);
        uid = -1;
    }
    if (uid === -1) {
        res.send({ code: 500, msg: "用户无权限" });
        return;
    }

    let resP =yield agentService.getMyPartnerNum(clubId,uid);
    let resM =yield agentService.getMyTrueMenberNum(clubId,uid);
    let resA =yield agentService.getAgetnClubAllNum(clubId);
    let result = {};
    result.code = 200;
    result.partner = resP;
    result.member = resM;
    result.playerNum = resA;
    result.msg = "success";
    res.send(result);

});

router.get('/weixin/agent/getAllPlayerNum',function(req,res){
    router.getAllPlayerNum(req,res).catch(function(e) {
        if(e instanceof BusiError){
            res.send({code:500, msg: e.message});
            return;
        }
        if(!res.finished) {
            console.logw("getClubInfo 发生异常 "+ e.message);
            res.send({code:500,msg:"网络异常，请稍后重试 "});
        }
    });
});